<template>
  <view class="edit">
    <!-- 标题 -->
    <view class="title">
      <input type="text" placeholder="请输入一个标题" v-model="artObj.title" placeholder-class="placeholderClass" />
    </view>
    <!-- 内容 -->
    <view class="content">
      <editor class="myEdit" placeholder="写点什么吧~~" show-img-size show-img-toolbar show-img-resize @ready="onReady"
        @statuschange="onStatuschange" @focus="edit_toolStatue">
      </editor>
    </view>
    <!-- 发布按钮 -->
    <view class="btnGroup">
      <!-- 没有标题是为警用状态 -->
      <u-button type="primary" :disabled="!artObj.title.length" @click="onSubmit">确认发表</u-button>
    </view>
    <!-- 富文本编辑器 选中高亮 -->
    <view class="tools" v-if="toolStatue">
      <view class="item" @click="icon_zitibiaoti">
        <text class="iconfont icon-zitibiaoti" :class="icon_zitibiaoti_bol?'active':''"></text>
      </view>
      <view class="item" @click="icon_zitijiacu">
        <text class="iconfont icon-zitijiacu" :class="icon_zitijiacu_bol?'active':''"></text>
      </view>
      <view class="item" @click="icon_zitixieti">
        <text class="iconfont  icon-zitixieti" :class="icon_zitixieti_bol?'active':''"></text>
      </view>
      <view class="item" @click="icon_fengexian"><text class="iconfont icon-fengexian"></text></view>
      <view class="item" @click="icon_charutupian">
        <text class="iconfont icon-charutupian"></text>
      </view>
      <view class="item" @click="icon_duigou_kuai">
        <text class="iconfont icon-duigou_kuai"></text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getImgSrc,
    getProvince
  } from "../../utils/tools.js"
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    ref,
    getCurrentInstance,
    reactive,
    toRefs
  } from "vue"
  const db = uniCloud.database()
  export default {
    setup() {
      const instance = getCurrentInstance(); // 获取组件实例
      const toolStatue = ref(false)
      const icon_zitibiaoti_bol = ref(false)
      const icon_zitijiacu_bol = ref(false)
      const icon_zitixieti_bol = ref(false)
      const button_bol = ref(true)
      const Obj = reactive({
        editorCtx: {},
        artObj: {
          title: '',
          content: '',
          description: '',
          picurls: '',
          province: '',
          last_modify_date: ''
        }
      })
      const doc_menu_state = ref(false)
      const doc_menu_id = ref(null)
      // 初始化 判断用户是编辑已发布文章还是编辑空文章
      onLoad((e) => {
        if (Object.keys(e).length) {
          editFun(e.id)
          doc_menu_id.value = e.id
        } else {
          getProvince().then(res => {
            console.log(res)
            Obj.artObj.province = res
          })
        }
      })
      // doc_menu 编辑
      const editFun = (id) => {
        db.collection("pyq_article").doc(id).get().then(res => {
          // 将已发布的标题 内容重新赋值到页面上
          Obj.artObj.title = res.result.data[0].title
          Obj.editorCtx.setContents({
            html: res.result.data[0].content
          })
        })
        doc_menu_state.value = true
      }
      // 添加分割线
      const icon_fengexian = () => {
        Obj.editorCtx.insertDivider()
      }
      //文字斜体
      const icon_zitixieti = () => {
        icon_zitixieti_bol.value = !icon_zitixieti_bol.value
        Obj.editorCtx.format("italic")
      }
      //文字标题化
      const icon_zitibiaoti = () => {
        icon_zitibiaoti_bol.value = !icon_zitibiaoti_bol.value
        Obj.editorCtx.format("header", "H1")
      }
      // 文字加粗
      const icon_zitijiacu = () => {
        icon_zitijiacu_bol.value = !icon_zitijiacu_bol.value
        Obj.editorCtx.format("bold")
      }
      // 图片上传
      const icon_charutupian = () => {
        // 从本地相册选择图片或使用相机拍照
        uni.chooseImage({
          success: async res => {
            uni.showLoading()
            //tempFiles =》 图片的本地文件列表
            for (let item of res.tempFiles) {
              //uploadFile =》 上传文件到云存储
              let suffix = item.path.substring(item.path.lastIndexOf("."));
              let randomName = Date.now() + "" + String(Math.random()).substr(3, 6) + suffix;
              let res = await uniCloud.uploadFile({
                filePath: item.path,
                cloudPath: item.name || randomName
              })
              // 插入图片
              Obj.editorCtx.insertImage({
                // fileID =》 文件唯一 ID，用来访问文件
                src: res.fileID,
              })
            }
            uni.hideLoading()
          }
        })
      }
      // 编辑完成，隐藏富文本编辑工具
      const icon_duigou_kuai = () => {
        toolStatue.value = false
      }
      // 点击提交
      const onSubmit = () => {
        Obj.editorCtx.getContents({
          success: res => {
            Obj.artObj.description = res.text.slice(0, 50)
            Obj.artObj.content = res.html
            Obj.artObj.picurls = getImgSrc(res.html)
            uni.showLoading({
              title: "发布中..."
            })
            if (doc_menu_state.value) {
              Obj.artObj.last_modify_date = Date.now()
              upDate()
            } else {
              Obj.artObj.last_modify_date = Date.now()
              addDate()
            }
          }
        })
      }
      // 更新数据数据 并跳转回首页
      const upDate = () => {
        db.collection("pyq_article").doc(doc_menu_id.value).update({
          ...Obj.artObj
        }).then(res => {
          uni.hideLoading()
          uni.showToast({
            title: "发布成功"
          })
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index/index"
            })
          }, 300)
        })
      }
      // 添加数据 并跳转回首页
      const addDate = () => {
        db.collection("pyq_article").add({
          ...Obj.artObj
        }).then(res => {
          uni.hideLoading()
          uni.showToast({
            title: "发布成功"
          })
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index/index"
            })
          }, 300)
        })
      }
      //初始化获取富文本编辑器上下文
      const onReady = () => {
        uni.createSelectorQuery().in(instance).select(".myEdit").fields({
          size: true,
          context: true
        }, res => {
          Obj.editorCtx = res.context
        }).exec()
      }
      // 当样式发送改变时
      const onStatuschange = (e) => {
        if (e.detail.hasOwnProperty('header')) {
          icon_zitibiaoti_bol.value = true
        } else {
          icon_zitibiaoti_bol.value = false
        }
      }
      // 获取焦点 显示编辑工具
      const edit_toolStatue = () => {
        toolStatue.value = true
      }
      return {
        toolStatue,
        edit_toolStatue,
        onReady,
        icon_fengexian,
        icon_zitibiaoti,
        icon_zitibiaoti_bol,
        icon_zitijiacu,
        icon_zitijiacu_bol,
        icon_zitixieti,
        icon_zitixieti_bol,
        icon_duigou_kuai,
        onStatuschange,
        icon_charutupian,
        ...toRefs(Obj),
        onSubmit
      }
    }
  }
</script>

<style lang="scss">
  //:deep() 深度选择器
  :deep(.ql-blank::before) {
    font-style: normal;
    color: #e0e0e0;
  }

  .edit {
    padding: 24rpx;

    .title {
      input {
        height: 120rpx;
        font-size: 46rpx;
        border-bottom: 1px solid #e4e4e4;
        margin-bottom: 30rpx;
      }

      .placeholderClass {
        color: #e0e0e0;
      }
    }

    .content {
      .myEdit {
        height: calc(100vh - 488rpx);
        margin-bottom: 30rpx;
      }
    }

    .tools {
      width: 100%;
      height: 80rpx;
      background: #fff;
      border-top: 1rpx solid #f4f4f4;
      position: fixed;
      left: 0;
      bottom: 0;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .iconfont {
        font-size: 36rpx;
        color: #333;

        &.active {
          color: #0199FE
        }
      }
    }
  }
</style>